<?php

use Swoole\Coroutine;
use Swoole\Coroutine\Channel;
use Swoole\Timer;
use Swoole\Coroutine\System;

Swoole\Coroutine::set([
    "max_coroutine" => 10000,
]);


class Crontab
{
    /**
     * @var int
     */
    protected $tickTime = 1;

    /**
     * @var int
     */
    protected $maxTask = 10;

    /**
     * @var Channel
     */
    protected $channel;

    public function __construct()
    {
        $this->channel = new Channel($this->maxTask);
    }

    /**
     * Timer
     */
    public function tick()
    {

        // 执行规则 ， 任务command  ，任务中的参数，任务状态[是否正在执行]
        // 操作: 编辑任务,删除任务,暂停任务(执行期间强制终止进程；下一次禁止执行）
        //日志系统:存储，展示（检索，搜索），删除日志，日志导入es 等等分析工具
        Timer::tick($this->tickTime * 1000, function ($timer_id) {
            //获取所有的tasks
            $tasks = [
                [
                    "timer_id" => $timer_id,
                    "task_name" => "task_name",
                    "rule" => "* * * * * *",
                    "command_string" => "/usr/bin/php  php_script.php",
                    "log_switch" => true,
                    "log_dir" => "test_dir",
                    "log_name" => "task_name_" . date("Y-m-d H:i:s") . ".log",
                    "storage_oss" => true,
                    "storage_api" => "",
                ],
                [
                    "timer_id" => $timer_id,
                    "task_name" => "task_name",
                    "rule" => "*/5 * * * * *",
                    "command_string" => "md5sum swoole.php",
                    "log_switch" => true,
                    "log_dir" => "test_dir",
                    "log_name" => "task_name_" . date("Y-m-d H:i:s") . ".log",
                    "storage_oss" => true,
                    "storage_api" => "",
                ]
            ];
            // Push task to channel
            foreach ($tasks as $task) {
                $this->channel->push($task);
            }
        });
    }

    /**
     * Exec Task
     */

    public function dispatch()
    {
        while (true) {
            $task = $this->channel->pop();
            var_dump($task);

            $cmd = $task["command_string"];
            //执行失败返回 false，执行成功返回数组，包含了进程退出的状态码、信号、输出内容。
            echo $cmd.PHP_EOL;
            $result = false;
            //$result = System::exec($cmd);
            if(!$result){
                echo date("Y-m-d H:i:s")." ,the task :".$cmd." exec false;".PHP_EOL;
            }else{
                var_dump($result);
            }
        }
    }
}

Co\run(function () {
    $task = new Crontab();
    $task->tick();
    $task->dispatch();
});

/**
 * http 回掉函数中创建协程容器
 * Class Http
 */
class Http
{

    public function __construct()
    {
    }


    public function onPen()
    {

    }
}
